<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of chatroom
 *
 * @author h16pham
 */

require_once 'sql_helper.class.php';
require_once 'message.class.php';

class Chatroom {
    //put your code here
    private $chatroom_id;
    private $chatroom_name;
    private $chatroom_description;
    private $session_id;
    
    public function getChatroom_id() {
        return $this->chatroom_id;
    }

    public function getChatroom_name() {
        return $this->chatroom_name;
    }

    public function getChatroom_description() {
        return $this->chatroom_description;
    }

    public function getSession_id() {
        return $this->session_id;
    }

    public function setChatroom_id($chatroom_id) {
        $this->chatroom_id = $chatroom_id;
    }

    public function setChatroom_name($chatroom_name) {
        $this->chatroom_name = $chatroom_name;
    }

    public function setChatroom_description($chatroom_description) {
        $this->chatroom_description = $chatroom_description;
    }

    public function setSession_id($session_id) {
        $this->session_id = $session_id;
    }

    function __construct($chatroom_id, $chatroom_name, $chatroom_description, $session_id) {
        $this->chatroom_id = $chatroom_id;
        $this->chatroom_name = $chatroom_name;
        $this->chatroom_description = $chatroom_description;
        $this->session_id = $session_id;
    }
    
    public static function sendMessage($chatroom_id, $user_id, $message_text) {
        $message_time = date("Y-m-d H:i:s");

        $statement = "INSERT INTO `C-dev`.`MESSAGE`
                    (`user_id`,
                    `chatroom_id`,
                    `message_text`,
                    `message_time`)
                    VALUES(
                    $user_id,
                    $chatroom_id,
                    '$message_text',
                    '$message_time');
                    ";
        
        echo $statement;
        
        SQLHelper::executeNonQuerry($statement);
    }
    
    public static function getMessagesByChatroom($chatroom_id)
    {
        //username: message_text
        $rs = new SplDoublyLinkedList();
        
        $statement = "SELECT message_id, user_id, userName, chatroom_id, message_text, message_time FROM `C-dev`.MESSAGE, `C-dev`.USER WHERE MESSAGE.user_id = USER.userID AND chatroom_id=$chatroom_id ORDER BY message_time LIMIT 50;";
        
        $result = SQLHelper::executeQuerry($statement);

        while ($row = mysql_fetch_array($result))
        {
            $message = new Message($row[0], $row[1], $row[2], $row[4], $row[5]);
            $rs->push($message);
        }
        
        return $rs;
    }
}
